# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 校区视图

校区管理相关的路由处理
包括校区CRUD操作、搜索、分页等功能
"""

from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, abort
from flask_login import login_required, current_user
from app.forms.campus_forms import (
    CampusCreateForm, CampusEditForm, CampusSearchForm,
    CampusDeleteForm, CampusBatchForm
)
from app.controllers.campus_controller import CampusController
from app.utils.decorators import super_admin_required, admin_required
from app.models.campus import Campus

# 创建校区蓝图
campus_bp = Blueprint('campus', __name__)


@campus_bp.route('/')
@campus_bp.route('/list')
@admin_required
def list():
    """
    校区列表页

    支持搜索、筛选、分页功能
    """
    form = CampusSearchForm()

    # 获取搜索参数
    page = request.args.get('page', 1, type=int)
    keyword = request.args.get('keyword', '')
    status = request.args.get('status', '')
    has_admin = request.args.get('has_admin', '')
    sort_by = request.args.get('sort_by', 'created_at_desc')

    # 设置表单默认值
    if request.method == 'GET':
        form.keyword.data = keyword
        form.status.data = status
        form.has_admin.data = has_admin
        form.sort_by.data = sort_by

    # 获取校区列表
    pagination, total = CampusController.get_campus_list(
        page=page,
        per_page=10,
        keyword=keyword,
        status=status,
        has_admin=has_admin,
        sort_by=sort_by
    )

    return render_template(
        'campus/list.html',
        form=form,
        pagination=pagination,
        campuses=pagination.items,
        total=total
    )


@campus_bp.route('/<int:id>')
@admin_required
def detail(id):
    """
    校区详情页

    显示校区完整信息和统计数据
    """
    campus = CampusController.get_campus_by_id(id)
    if not campus:
        flash('校区不存在', 'error')
        return redirect(url_for('campus.list'))

    # 获取校区统计信息
    statistics = CampusController.get_campus_statistics(id)

    # 检查关联数据（用于显示删除按钮）
    associations = CampusController.check_campus_associations(id)

    return render_template(
        'campus/detail.html',
        campus=campus,
        statistics=statistics,
        associations=associations
    )


@campus_bp.route('/create', methods=['GET', 'POST'])
@super_admin_required
def create():
    """
    创建校区页

    只有超级管理员可以创建校区
    """
    form = CampusCreateForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            # 获取表单数据
            form_data = {
                'name': form.name.data,
                'address': form.address.data,
                'phone': form.phone.data,
                'email': form.email.data,
                'admin_id': form.admin_id.data,
                'capacity': form.capacity.data,
                'area': form.area.data,
                'description': form.description.data,
                'facilities': form.facilities.data,
                'operating_hours': form.operating_hours.data,
                'is_active': form.is_active.data,
            }

            # 创建校区
            success, result = CampusController.create_campus(
                form_data,
                form.photo.data
            )

            if success:
                flash(f'校区"{result.name}"创建成功！', 'success')
                return redirect(url_for('campus.detail', id=result.id))
            else:
                flash(f'创建失败：{result}', 'error')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(f'{form[field].label.text}: {error}', 'error')

    return render_template('campus/create.html', form=form)


@campus_bp.route('/<int:id>/edit', methods=['GET', 'POST'])
@super_admin_required
def edit(id):
    """
    编辑校区页

    只有超级管理员可以编辑校区
    """
    campus = CampusController.get_campus_by_id(id)
    if not campus:
        flash('校区不存在', 'error')
        return redirect(url_for('campus.list'))

    form = CampusEditForm(campus=campus)

    if request.method == 'GET':
        # 填充表单数据
        form.name.data = campus.name
        form.address.data = campus.address
        form.phone.data = campus.phone
        form.email.data = campus.email
        form.admin_id.data = campus.admin_id or 0
        form.capacity.data = campus.capacity
        form.area.data = campus.area
        form.description.data = campus.description
        form.facilities.data = campus.facilities
        form.operating_hours.data = campus.operating_hours
        form.is_active.data = (campus.status == 'active')

    if request.method == 'POST':
        if form.validate_on_submit():
            # 获取表单数据
            form_data = {
                'name': form.name.data,
                'address': form.address.data,
                'phone': form.phone.data,
                'email': form.email.data,
                'admin_id': form.admin_id.data,
                'capacity': form.capacity.data,
                'area': form.area.data,
                'description': form.description.data,
                'facilities': form.facilities.data,
                'operating_hours': form.operating_hours.data,
                'is_active': form.is_active.data,
            }

            # 更新校区
            success, error_msg = CampusController.update_campus(
                campus,
                form_data,
                form.photo.data
            )

            if success:
                flash(f'校区"{campus.name}"更新成功！', 'success')
                return redirect(url_for('campus.detail', id=campus.id))
            else:
                flash(f'更新失败：{error_msg}', 'error')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(f'{form[field].label.text}: {error}', 'error')

    return render_template('campus/edit.html', form=form, campus=campus)


@campus_bp.route('/<int:id>/delete', methods=['GET', 'POST'])
@super_admin_required
def delete(id):
    """
    删除校区页

    只有超级管理员可以删除校区
    """
    campus = CampusController.get_campus_by_id(id)
    if not campus:
        flash('校区不存在', 'error')
        return redirect(url_for('campus.list'))

    # 检查关联数据
    associations = CampusController.check_campus_associations(id)

    form = CampusDeleteForm()
    form.campus_id.data = id

    if request.method == 'POST':
        if form.validate_on_submit():
            if not associations['can_delete']:
                flash(associations['message'], 'error')
                return redirect(url_for('campus.detail', id=id))

            success, error_msg = CampusController.delete_campus(id)

            if success:
                flash(f'校区"{campus.name}"已删除', 'success')
                return redirect(url_for('campus.list'))
            else:
                flash(f'删除失败：{error_msg}', 'error')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(error, 'error')

    return render_template(
        'campus/delete_confirm.html',
        form=form,
        campus=campus,
        associations=associations
    )


@campus_bp.route('/batch', methods=['POST'])
@super_admin_required
def batch_operation():
    """
    批量操作校区

    只有超级管理员可以执行批量操作
    """
    form = CampusBatchForm()

    if form.validate_on_submit():
        try:
            campus_ids = [int(id.strip()) for id in form.campus_ids.data.split(',') if id.strip()]
            action = form.action.data

            success_count, fail_count, errors = CampusController.batch_operation(
                campus_ids, action
            )

            # 构建结果消息
            if success_count > 0:
                action_text = {
                    'activate': '启用',
                    'deactivate': '禁用',
                    'delete': '删除'
                }.get(action, '操作')
                flash(f'成功{action_text}{success_count}个校区', 'success')

            if fail_count > 0:
                flash(f'{fail_count}个校区操作失败', 'warning')
                for error in errors[:5]:  # 只显示前5个错误
                    flash(error, 'error')

        except Exception as e:
            flash(f'批量操作失败：{str(e)}', 'error')
    else:
        # 显示表单验证错误
        for field, errors in form.errors.items():
            for error in errors:
                flash(error, 'error')

    return redirect(url_for('campus.list'))


@campus_bp.route('/api/search')
@admin_required
def api_search():
    """
    校区搜索API

    用于AJAX请求获取校区列表
    """
    keyword = request.args.get('keyword', '')
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)

    try:
        pagination, total = CampusController.get_campus_list(
            page=page,
            per_page=per_page,
            keyword=keyword
        )

        campuses_data = []
        for campus in pagination.items:
            admin_name = ''
            from app.models.user import User
            admin = User.query.filter_by(campus_id=campus.id, role='campus_admin').first()
            if admin:
                admin_name = admin.real_name

            campuses_data.append({
                'id': campus.id,
                'name': campus.name,
                'address': campus.address,
                'phone': campus.phone,
                'admin_name': admin_name,
                'capacity': campus.capacity,
                'status': campus.status,
                'created_at': campus.created_at.strftime('%Y-%m-%d') if campus.created_at else ''
            })

        return jsonify({
            'success': True,
            'data': campuses_data,
            'pagination': {
                'page': pagination.page,
                'pages': pagination.pages,
                'per_page': pagination.per_page,
                'total': pagination.total,
                'has_prev': pagination.has_prev,
                'has_next': pagination.has_next
            }
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@campus_bp.route('/api/<int:id>/statistics')
@admin_required
def api_statistics(id):
    """
    校区统计API

    获取校区的统计信息
    """
    campus = CampusController.get_campus_by_id(id)
    if not campus:
        return jsonify({'success': False, 'error': '校区不存在'}), 404

    try:
        statistics = CampusController.get_campus_statistics(id)
        return jsonify({
            'success': True,
            'data': statistics
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@campus_bp.route('/api/<int:id>/associations')
@admin_required
def api_associations(id):
    """
    校区关联数据API

    检查校区的关联数据
    """
    campus = CampusController.get_campus_by_id(id)
    if not campus:
        return jsonify({'success': False, 'error': '校区不存在'}), 404

    try:
        associations = CampusController.check_campus_associations(id)
        return jsonify({
            'success': True,
            'data': associations
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500